/*
 * @(#)IOUtils.java, 2009-2-22
 *
 * Copyright 2009 SuperV System Integration CO., LTD. All rights reserved.
 */
package org.lex.utils;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 
 * 
 * @author Liu Er Xiao
 * @version 1.0, 2009-2-22
 */
public class IOUtils {
	private static final int BUFFER_SIZE = 64 * 1024;

	private static final long DELETE_FILE_INTERVAL = 500;
	private static final int DELETE_FILE_RETRY_COUNT = 50;

	public static void closeQuietly(Closeable close) {
		if (null == close) {
			return;
		}
		try {
			close.close();
		} catch (Exception e) {
			// don't care exception
		}
	}

	public static void deleteQuietly(final File file) {
		if (null == file || false == file.exists()) {
			return;
		}
		try {
			if (true == file.delete()) {
				return;
			}
		} catch (Exception e) {
		}
		final Timer deleteFileTimer = new Timer(true);
		TimerTask deleteFileTask = new TimerTask() {
			private int count = 0;

			@Override
			public void run() {
				boolean deleted = false;
				try {
					deleted = file.delete();
				} catch (Exception e) {
				}
				if (true == deleted) {
					stop();
				} else if (count >= DELETE_FILE_RETRY_COUNT) {
					stop();
					file.deleteOnExit();
				} else {
					count++;
				}
			}

			private void stop() {
				this.cancel();
				deleteFileTimer.cancel();
				deleteFileTimer.purge();
			}
		};
		deleteFileTimer.schedule(deleteFileTask, DELETE_FILE_INTERVAL, DELETE_FILE_INTERVAL);
	}

	public static void copyStream(InputStream in, OutputStream out) throws IOException {
		byte[] buf = new byte[IOUtils.BUFFER_SIZE];
		int len = 0;
		while (-1 != (len = in.read(buf))) {
			out.write(buf, 0, len);
		}
	}
}
